package com.qili.controller.sys;


import com.alibaba.fastjson.JSONObject;
import com.qili.annotation.Bookmark;
import com.qili.base.entity.BasePathConfig;
import com.qili.base.service.BasePathConfigService;
import com.qili.core.utils.DictTypes;
import com.qili.core.utils.DictUtil;
import com.qili.core.utils.FileUtils;
import com.qili.entity.affaircase.AffairCase;
import com.qili.entity.affaircase.dto.AffairRecordDTO;
import com.qili.entity.base.BaseCompany;
import com.qili.entity.base.BaseDict;
import com.qili.entity.supervisor.*;
import com.qili.entity.supervisor.dto.SupervisorFileDTO;
import com.qili.entity.sys.SysUser;
import com.qili.service.SysUserService;
import com.qili.service.affairCase.AffairCaseService;
import com.qili.service.affairCase.AffairRecordService;
import com.qili.service.base.BaseCompanyService;
import com.qili.service.base.BaseDictService;
import com.qili.service.base.SupervisorProjectMilepostService;
import com.qili.service.base.SupervisorProjectStageService;
import com.qili.service.supervisor.*;
import com.qili.util.*;
import com.zhuozhengsoft.pageoffice.*;
import com.zhuozhengsoft.pageoffice.wordwriter.*;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.assertj.core.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.*;

import static java.util.Objects.isNull;

/**
 * @author Administrator
 */
@Component
@Slf4j
@RequestMapping("/sys/office")
public class PageOfficeController<T> {

    @Autowired
    SupervisorFileService supervisorFileService;
    @Autowired
    SupervisorFileTempService supervisorFileTempService;
    @Autowired
    SupervisorProjectFormsService supervisorProjectFormsService;
    @Autowired
    BasePathConfigService basePathConfigService;
    @Autowired
    SupervisorProjectFormsDataService supervisorProjectFormsDataService;
    @Autowired
    SupervisorProjectEvaluationService supervisorProjectEvaluationService;
    @Autowired
    SupervisorProjectEvaluationScoreService supervisorProjectEvaluationScoreService;
    @Autowired
    private SysUserService userService;
    @Autowired
    private BaseDictService baseDictService;
    @Autowired
    private SupervisorProjectService supervisorProjectService;
    @Autowired
    private ProjectLeaderService projectLeaderService;
    @Autowired
    private SupervisorProjectMilepostService supervisorProjectMilepostService;

    @Autowired
    private SupervisorProjectStageService supervisorProjectStageService;
    @Autowired
    private ProjectUnitConstructionService projectUnitConstructionService;
    @Autowired
    private UploadUtil uploadUtil;
    @Autowired
    private ProjectBigEventService projectBigEventService;
    @Autowired
    private ProjectSealRecordService projectSealRecordService;
    @Autowired
    private BaseCompanyService companyService;
    @Autowired
    private AffairCaseService affairCaseService;
    @Autowired
    private AffairRecordService affairRecordService;
    @Autowired
    private   ProjectContractService  projectContractService;
    @Autowired
    SysUserService sysUserService;


    /**
     * @param
     * @Author:Zhangshuo
     * @Description:
     * @Date:21:13 2020/11/14
     */
    @GetMapping(value = "index")
    public String showindex() {
        return "/personcenter/index";
    }

    /**
     * @param request
     * @param map
     * @Author:Zhangshuo
     * @Description:打开Word
     * @Date:14:59 2020/11/16
     */
    @RequestMapping("/openword")
    public String openWord(HttpServletRequest request, Map<String, Object> map) {
        try {
            FileEnum fileEnum = getRequestParam(request);
            String AsUrl = null;
            switch (fileEnum) {
                case FL_ONLY:
                    AsUrl = openWordOnly(request, map, fileEnum);
                    break;
                case FL_FORMS:
                    AsUrl = openWordForProjectById(request, map, fileEnum);
                    break;
                case FL_FILES:
                    AsUrl = openWordOnly(request, map, fileEnum);
                    break;
                case FL_EVAL:
                    AsUrl = openWordByEVAL(request, map, fileEnum);
                    break;
                case FL_ONLYREAD:
                    AsUrl = openWordOnlyRead(request, map);
                    break;
                case FL_INSERT_CHILD_IMG:
                    AsUrl = openWordAndInsertChildImg(request, map, fileEnum);
                    break;
                case FL_INSERT_CHILD_WORD:
                    AsUrl = openWordAndInsertChildWord(request, map, fileEnum);
                    break;
                case FL_SIGN:
                    AsUrl = openWordAndSign(request, map, fileEnum);
                    break;
                case FL_SEAL:
                    AsUrl = openWordAndSeal(request, map, fileEnum);
                    break;
                case FL_SEAL_YZ:
                    AsUrl = openWordAndSealYz(request, map, fileEnum);
                    break;
                case FL_Edit:
                    AsUrl = openWordEdit(request, map, fileEnum);
                    break;
                case FL_SEAL_RECORD:
                    AsUrl = openWordAndSealRecord(request, map, fileEnum);
                    break;
                default:
                    AsUrl = openWordOnly(request, map, fileEnum);
            }
            return AsUrl;
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("emsg", e.getMessage());
            return "/office/error";
        }
    }
    /**
    * @Author:zhaoyongke
    * @Description:打开临时表
    * @param request
    * @param map
    * @Date:13:24 2021/4/2
    */
    @RequestMapping("/openwordTemp")
    public String openwordTemp(HttpServletRequest request, Map<String, Object> map) {

        try {
            FileEnum fileEnum = getRequestParamTemp(request);
            String AsUrl = null;
            switch (fileEnum) {
                case FL_ONLY:
                    AsUrl = openWordOnly(request, map, fileEnum);
                    break;
                default:
                    AsUrl = openWordOnly(request, map, fileEnum);
            }
            return AsUrl;
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("emsg", e.getMessage());
            return "/office/error";
        }



    }


    /**
     * 打开文档（只读）
     *
     * @param request
     * @return
     */
    public String openWordOnlyRead(HttpServletRequest request, Map<String, Object> map) {
        try {
            //文件路径
            String speid = request.getParameter("speid");
            if (StringUtil.isNotBlank(speid)) {
                SupervisorFile supervisorFile = new SupervisorFile();
                supervisorFile.setLinkId(speid);
                List<SupervisorFile> select = supervisorFileService.select(supervisorFile);
                String AsFileName = "";
                if (select.size() > 0) {
                    AsFileName = select.get(0).getUrl();
                }
                //初始化PageOfficeCtrl
                PageOfficeCtrl poCtrl = new PageOfficeCtrl(request);
                poCtrl.setOfficeVendor(OfficeVendorType.AutoSelect);
                //设置服务页面
                poCtrl.setServerPage(request.getContextPath() + "/poserver.zz");
                //打开word
                poCtrl.webOpen("file://" + AsFileName, OpenModeType.docReadOnly, "张三");
                map.put("pageoffice", poCtrl.getHtmlCode("PageOfficeCtrl1"));
                return "/office/word";
            } else {
                return "/office/error";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "/office/error";
        }
    }

    /**
     * @param request
     * @param map
     * @Description:打开word 评价
     * @Author:Zhangshuo
     * @Date:21:12 2020/11/14
     */
    public String openWordByEVAL(HttpServletRequest request, Map<String, Object> map, FileEnum fileEnum) {
        try {
            //项目id
            String spId = request.getParameter("spid");
            //评价表头id
            String speid = request.getParameter("speid");
            //创建人类型
            // source 001   aIndex  1  固定为对实施人员   对监理项目经理的评价 source 001   aIndex  2  固定为对市场人员   对项目发布人的评价  source 003              固定为对供方       对监理项目经理的评价
            String source = request.getParameter("source");
            String aindex = request.getParameter("aindex");
            //base_pathconfig表id
            //根据参数获取实体类
            SupervisorProjectEvaluation evaluation = supervisorProjectEvaluationService.selectByPrimaryKey(speid);
            SupervisorProjectEvaluationScore selectScore = new SupervisorProjectEvaluationScore();
            selectScore.setSpeId(evaluation.getSpeId());
            List<SupervisorProjectEvaluationScore> scoreList = supervisorProjectEvaluationScoreService.selectOrder(selectScore);
            SysUser creator = userService.selectByPrimaryKey(evaluation.getCreateBy());
            String companyName = creator.getCompanyName();
            //根据该值去base_company表中查询一下:
            BaseCompany baseCompany = new BaseCompany();
            baseCompany.setBcId(companyName);
            BaseCompany baseCompany1 = companyService.selectByPrimaryKey(baseCompany);
            if (baseCompany1 != null && StringUtils.isNotBlank(baseCompany1.getBcName())) {
                creator.setCompanyName(baseCompany1.getBcName());
            }
            evaluation.setCreatorName(creator.getRealName());
            evaluation.setCreatorComName(creator.getCompanyName());

            BasePathConfig basePathConfig = basePathConfigService.selectByPrimaryKey(fileEnum.getFilePathId());

            if (!isNull(scoreList) && (!isNull(basePathConfig))) {
                //需要打开的文件名
                String AsFileName = basePathConfig.getBfcTemplateFile();
                WordDocument doc = new WordDocument();
                PageOfficeCtrl poCtrl;
                try {
                    //禁用右击事件
                    doc.setDisableWindowRightClick(true);
                    doc.openDataRegion("PO_year").setValue(DateUtil.yearOf(evaluation.getCreateDate()) + "");
                    doc.openDataRegion("PO_month").setValue(DateUtil.monthOf(evaluation.getCreateDate()) + "");
                    doc.openDataRegion("PO_score").setValue(evaluation.getScore());
                    //加载Region
                    loadRegion(doc, evaluation, scoreList);
                    //初始化PageOfficeCtrl
                    poCtrl = new PageOfficeCtrl(request);
                    poCtrl.setOfficeVendor(OfficeVendorType.AutoSelect);
                    //添加自定义保存按钮
                    poCtrl.addCustomToolButton("保存", "Save", 1);
                    poCtrl.setJsFunction_AfterDocumentOpened("afterOpenEva()");
                    //设置服务页面
                    poCtrl.setServerPage(request.getContextPath() + "/poserver.zz");
                    poCtrl.setWriter(doc);
                    String AsTmp = fileEnum.getParam();
                    //设置处理文件保存的请求方法
                    poCtrl.setSaveFilePage("/sys/office/save" + (StringUtil.isBlank(AsTmp) ? "" : ("?" + AsTmp)));
                    //打开word
                    poCtrl.webOpen("file://" + AsFileName, OpenModeType.docReadOnly, "张三");
                    map.put("pageoffice", poCtrl.getHtmlCode("PageOfficeCtrl1"));
                } finally {
                    // doc.
                }
            }
            return "/office/word";
        } catch (Exception e) {
            e.printStackTrace();
            return "/office/error";
        }
    }

    /**
     * @param request
     * @param map
     * @param fileEnum
     * @Description: 打开word并插入子word
     * @Author:Zhangshuo
     * @Date:23:17 2020-12-15
     */
    public String openWordAndInsertChildWord(HttpServletRequest request, Map<String, Object> map, FileEnum fileEnum) {
        try {
            //需要打开的文件名
            String AsFileName = fileEnum.getFilePath();
            if (StringUtil.isNotBlank(AsFileName)) {
                WordDocument doc = new WordDocument();
                PageOfficeCtrl poCtrl;
                //禁用右击事件
                doc.setDisableWindowRightClick(true);
                //加载Region
                //根据主文件获取子文件
                SupervisorFile supervisorFile = new SupervisorFile();
                supervisorFile.setParentId(fileEnum.getFileId());
                List<SupervisorFile> AlstFiles = supervisorFileService.select(supervisorFile);
                StringBuilder AsbImgs = new StringBuilder();
                if (!isNull(AlstFiles)) {
                    for (SupervisorFile file : AlstFiles) {
                        AsbImgs.append("[word]" + file.getUrl() + "[/word]");
                    }
                }
                DataRegion AdrItem = doc.openDataRegion(fileEnum.getFileTag());
                AdrItem.setValue(AsbImgs.toString());
                //初始化PageOfficeCtrl
                poCtrl = new PageOfficeCtrl(request);
                poCtrl.setOfficeVendor(OfficeVendorType.AutoSelect);
                //设置服务页面
                poCtrl.setServerPage(request.getContextPath() + "/poserver.zz");
                //添加自定义保存按钮
                poCtrl.addCustomToolButton("保存", "Save", 1);
                poCtrl.setJsFunction_AfterDocumentSaved("AfterDocumentSaved()");
                //添加自定义盖章按钮
                //poCtrl.addCustomToolButton("盖章", "AddSeal", 2);
                poCtrl.setWriter(doc);
                String AsTmp = fileEnum.getParam();
                //设置处理文件保存的请求方法
                poCtrl.setSaveFilePage("/sys/office/save" + (StringUtil.isBlank(AsTmp) ? "" : ("?" + AsTmp)));

                //打开word
                poCtrl.webOpen("file://" + AsFileName, OpenModeType.docNormalEdit, "张三");
                map.put("pageoffice", poCtrl.getHtmlCode("PageOfficeCtrl1"));

                return "/office/word";
            } else {
                return "/office/error";
            }

        } catch (Exception e) {
            e.printStackTrace();
            return "/office/error";
        }
    }

    /**
     * @param request
     * @param map
     * @param fileEnum
     * @Description: 打开word并插入图片
     * @Author:Zhangshuo
     * @Date:23:17 2020-12-15
     */
    public String openWordAndInsertChildImg(HttpServletRequest request, Map<String, Object> map, FileEnum fileEnum) {
        try {
            //需要打开的文件名
            String AsFileName = fileEnum.getFilePath();
            if (StringUtil.isNotBlank(AsFileName)) {
                WordDocument doc = new WordDocument();
                PageOfficeCtrl poCtrl;
                //禁用右击事件
                doc.setDisableWindowRightClick(true);
                //加载Region
                LoadChildImgRegion(fileEnum, doc);
                //初始化PageOfficeCtrl
                poCtrl = new PageOfficeCtrl(request);
                poCtrl.setOfficeVendor(OfficeVendorType.AutoSelect);
                //设置服务页面
                poCtrl.setServerPage(request.getContextPath() + "/poserver.zz");
                //添加自定义保存按钮
                poCtrl.addCustomToolButton("保存", "Save", 1);
                poCtrl.setJsFunction_AfterDocumentSaved("AfterDocumentSaved()");
                //添加自定义盖章按钮
                //poCtrl.addCustomToolButton("盖章", "AddSeal", 2);
                poCtrl.setWriter(doc);
                String AsTmp = fileEnum.getParam();
                //设置处理文件保存的请求方法
                poCtrl.setSaveFilePage("/sys/office/save" + (StringUtil.isBlank(AsTmp) ? "" : ("?" + AsTmp)));

                //打开word
                poCtrl.webOpen("file://" + AsFileName, OpenModeType.docNormalEdit, "张三");
                map.put("pageoffice", poCtrl.getHtmlCode("PageOfficeCtrl1"));

                return "/office/word";
            } else {
                return "/office/error";
            }

        } catch (
                Exception e) {
            e.printStackTrace();
            return "/office/error";
        }
    }

    /**
     * @param fileEnum
     * @param doc
     * @Description:
     * @Author:Zhangshuo
     * @Date:11:40 2020-12-16
     */
    private void LoadChildImgRegion(FileEnum fileEnum, WordDocument doc) {
        String AsTagName = fileEnum.getFileTag();
        DataRegion AdrItem = doc.openDataRegion(AsTagName);
        AdrItem.setValue("");
        //根据主文件获取子文件
        SupervisorFile supervisorFile = new SupervisorFile();
        supervisorFile.setParentId(fileEnum.getFileId());
        List<SupervisorFile> AlstFiles = supervisorFileService.select(supervisorFile);
        if (!isNull(AlstFiles)) {
            for (int i = 0; i < AlstFiles.size(); i++) {
                SupervisorFile file = AlstFiles.get(i);
                if (!isNull(file)) {
                    String AsTmp = com.qili.util.DateUtil.getCurrentDateTimeStringNoSpliter() + i;
                    String AsTxtPostion = "PO_IMG_TXTPOS" + AsTmp;
                    DataRegion AdrNewText = doc.createDataRegion(AsTxtPostion, DataRegionInsertType.Before, AsTagName);
                    AdrNewText.setValue("\n\n部位：" + file.getPositionName());
                    ParagraphFormat paragraphFormat = AdrNewText.getParagraphFormat();
                    paragraphFormat.setAlignment(WdParagraphAlignment.wdAlignParagraphLeft);
                    String AsNamePosition = "PO_IMG_NAMEPOS" + AsTmp;
                    DataRegion AdrPicName = doc.createDataRegion(AsNamePosition, DataRegionInsertType.After, AsTxtPostion);
                    AdrNewText.setValue("\n\n文件名称：" + file.getFileName() + "\r\n");
                    ParagraphFormat paragraphNameFormat = AdrPicName.getParagraphFormat();
                    paragraphNameFormat.setAlignment(WdParagraphAlignment.wdAlignParagraphLeft);
                    String AsImgPostion = "PO_IMG_POS" + AsTmp;
                    DataRegion AdrNewImg = doc.createDataRegion(AsImgPostion, DataRegionInsertType.After, AsTxtPostion);
                    AdrNewImg.setValue("[image]file://" + file.getUrl() + "[/image]");
                }
            }
        }
    }

    /**
     * @param request
     * @param map
     * @param fileEnum
     * @Description: 打开word并插入图片
     * @Author:Zhangshuo
     * @Date:23:17 2020-12-15
     */
    public String openWordAndSign(HttpServletRequest request, Map<String, Object> map, FileEnum fileEnum) {
        try {
            //需要打开的文件名
            String AsFileName = fileEnum.getFilePath();
            if (StringUtil.isNotBlank(AsFileName)) {
                WordDocument doc = new WordDocument();
                PageOfficeCtrl poCtrl;
                //禁用右击事件
                doc.setDisableWindowRightClick(true);
                /*根据当前登录人获取个人中心上传的电子签名 */
                JSONObject jsonObject = getTagAndUrlSign();
                String url = jsonObject.get("url") + "";
                if (StringUtil.isBlank(url)) {
                    throw new Exception("请维护电子签名信息！");
                }
                String AsbImgs = "[image]file://" + url + "[/image]";
                DataRegion AdrItem = doc.openDataRegion(jsonObject.get("tag") + "");
                AdrItem.setValue(AsbImgs);
                DataRegion AsbIDate = doc.openDataRegion(jsonObject.get("tag") + "_DATE");
                AsbIDate.setValue(com.qili.util.DateUtil.formatDate(new Date(), "yyyy年MM月dd日"));

                //初始化PageOfficeCtrl
                poCtrl = new PageOfficeCtrl(request);
                poCtrl.setOfficeVendor(OfficeVendorType.AutoSelect);
                //设置服务页面
                poCtrl.setServerPage(request.getContextPath() + "/poserver.zz");
                //添加自定义保存按钮
                poCtrl.addCustomToolButton("保存", "Save", 1);
                poCtrl.setJsFunction_AfterDocumentSaved("AfterDocumentSaved()");
                //添加自定义盖章按钮
                //poCtrl.addCustomToolButton("盖章", "AddSeal", 2);
                poCtrl.setWriter(doc);
                String AsTmp = fileEnum.getParam();
                //设置处理文件保存的请求方法
                poCtrl.setSaveFilePage("/sys/office/save" + (StringUtil.isBlank(AsTmp) ? "" : ("?" + AsTmp)));

                //打开word
                poCtrl.webOpen("file://" + AsFileName, OpenModeType.docNormalEdit, "张三");
                map.put("pageoffice", poCtrl.getHtmlCode("PageOfficeCtrl1"));

                return "/office/word";
            } else {
                return "/office/error";
            }

        } catch (
                Exception e) {
            e.printStackTrace();
            return "/office/error";
        }
    }

    /**
     * @param request
     * @param map
     * @param fileEnum
     * @Description: 打开word并插入图片
     * @Author:Zhangshuo
     * @Date:23:17 2020-12-15
     */
    public String openWordAndSeal(HttpServletRequest request, Map<String, Object> map, FileEnum fileEnum) {
        try {
            //需要打开的文件名
            String AsFileName = fileEnum.getFilePath();
            if (StringUtil.isNotBlank(AsFileName)) {
                WordDocument doc = new WordDocument();
                PageOfficeCtrl poCtrl;
                //禁用右击事件
                doc.setDisableWindowRightClick(true);
                /*盖章操作*/
                addStamp(fileEnum, doc);
                //初始化PageOfficeCtrl
                poCtrl = new PageOfficeCtrl(request);
//                poCtrl.setOfficeVendor(OfficeVendorType.AutoSelect);
                //设置服务页面
                poCtrl.setServerPage(request.getContextPath() + "/poserver.zz");
                //添加自定义保存按钮
                poCtrl.addCustomToolButton("保存", "Save", 1);
                poCtrl.setJsFunction_AfterDocumentSaved("AfterDocumentSaved()");
                //添加自定义盖章按钮
                //poCtrl.addCustomToolButton("盖章", "AddSeal", 2);
                poCtrl.setWriter(doc);
                String AsTmp = fileEnum.getParam();
                //设置处理文件保存的请求方法
                poCtrl.setSaveFilePage("/sys/office/save" + (StringUtil.isBlank(AsTmp) ? "" : ("?" + AsTmp)));

                //打开word
                poCtrl.webOpen("file://" + AsFileName, OpenModeType.docNormalEdit, "张三");
                map.put("pageoffice", poCtrl.getHtmlCode("PageOfficeCtrl1"));

                return "/office/word";
            } else {
                return "/office/error";
            }

        } catch (
                Exception e) {
            System.out.println("yiuyiuicodufioduc didf i  ");
            e.printStackTrace();
            request.setAttribute("emsg", e.getMessage());
            return "/office/error";
        }
    }

    /**
     * @param request
     * @param map
     * @param fileEnum
     * @Author:zhaoyongke
     * @Description: 业主签章操作
     * @Date:11:08 2021/1/29
     */
    public String openWordAndSealYz(HttpServletRequest request, Map<String, Object> map, FileEnum fileEnum) {
        try {
            //需要打开的文件名
            String AsFileName = fileEnum.getFilePath();
            if (StringUtil.isNotBlank(AsFileName)) {
                WordDocument doc = new WordDocument();
                PageOfficeCtrl poCtrl;
                //禁用右击事件
                doc.setDisableWindowRightClick(true);
                String fileId = fileEnum.getFileId();
                /*盖章操作*/
                SupervisorFile file = new SupervisorFile();
                file.setParentId(fileId);
                file.setType("113");
                List<SupervisorFile> fileList = supervisorFileService.select(file);
                String url = "";
                if (fileList.size() > 0) {
                    url = fileList.get(0).getUrl();
                }
                String AsbImgs = "[image]file://" + url + "[/image]";
                /*文档后面追加 扫描件图片*/
                DataRegion dr2 = doc.createDataRegion("PO_dr2", DataRegionInsertType.After, "[end]");
                dr2.setValue(AsbImgs);
                //初始化PageOfficeCtrl
                poCtrl = new PageOfficeCtrl(request);
                poCtrl.setOfficeVendor(OfficeVendorType.AutoSelect);
                //设置服务页面
                poCtrl.setServerPage(request.getContextPath() + "/poserver.zz");
                //添加自定义保存按钮
                poCtrl.addCustomToolButton("保存", "Save", 1);
                poCtrl.setJsFunction_AfterDocumentOpened("afterOpenEva()");
                //添加自定义盖章按钮
                //poCtrl.addCustomToolButton("盖章", "AddSeal", 2);
                poCtrl.setWriter(doc);
                String AsTmp = fileEnum.getParam();
                //设置处理文件保存的请求方法
                poCtrl.setSaveFilePage("/sys/office/save" + (StringUtil.isBlank(AsTmp) ? "" : ("?" + AsTmp)));

                //打开word
                poCtrl.webOpen("file://" + AsFileName, OpenModeType.docReadOnly, "张三");
                map.put("pageoffice", poCtrl.getHtmlCode("PageOfficeCtrl1"));

                return "/office/word";
            } else {
                return "/office/error";
            }

        } catch (
                Exception e) {
            e.printStackTrace();
            request.setAttribute("emsg", e.getMessage());
            return "/office/error";
        }
    }

    public String openWordAndSealRecord(HttpServletRequest request, Map<String, Object> map, FileEnum fileEnum) {
        try {
            //需要打开的文件名
            String AsFileName = fileEnum.getFilePath();
            if (StringUtil.isNotBlank(AsFileName)) {
                //文件格式
                Boolean isdic=true;
                WordDocument doc = new WordDocument();
                PageOfficeCtrl poCtrl;
                //禁用右击事件
                doc.setDisableWindowRightClick(true);
                //  根据后缀名判断 如果是 doc 或 docx的文件 则 直接把 模板文件合并到文件中，如果是其他类型的文件则 单独生成一个 文件
                String fileId = fileEnum.getFileId();
                String filePath = fileEnum.getFilePath();
                SupervisorFile file = supervisorFileService.selectByPrimaryKey(fileId);
                int suffixLen = AsFileName.lastIndexOf(".");
                String hztype = AsFileName.substring(suffixLen, AsFileName.length()).toLowerCase();
                String copypath="";
                String newfileId="";
                if(!hztype.equals(".doc")  && !hztype.equals(".docx")  ){
                    // 复制一个模板文件
                    String superiorId = file.getSuperiorId();
                    SupervisorFile filedir = supervisorFileService.selectByPrimaryKey(superiorId);
                    // 文件夹路径
                    String dirurl = filedir.getUrl();
                    copypath=dirurl+File.separator+file.getId()+"报审表.docx";
                    // 没有则生成一个记录
                    SupervisorFile  filbs=new SupervisorFile();
                    filbs.setUrl(copypath);
                    filbs.setProjectId(file.getProjectId());
                    List<SupervisorFile> select = supervisorFileService.select(filbs);
                    if(select!=null  &&  select.size()>0){
                            SupervisorFile supervisorFile = select.get(0);
                            newfileId=supervisorFile.getId();
                    }else{
                        SupervisorFile  filedto=new SupervisorFile();
                        filedto.setFileName(file.getFileName()+"_报审表.docx");
                        filedto.setFileType(".docx");
                        filedto.setType("1234");
                        filedto.setCreateBy(CommonUtil.getUserId());
                        filedto.setCreateDate(new Date());
                        filedto.setUrl(copypath);
                        filedto.setInd(1);
                        filedto.setParentId(file.getId());
                        filedto.setProjectId(file.getProjectId());// 项目id
                        filedto.setSpmId(file.getSpmId());// 里程id
                        filedto.setStageId(file.getStageId());// 阶段id
                        supervisorFileService.insert(filedto);
                        newfileId=filedto.getId();
                        supervisorFileService.setFilePathDics(filedto);
                    }


                    isdic=false;
                }
                /*盖章操作*/
                addStampRecord(fileEnum, doc,copypath);
                //初始化PageOfficeCtrl
                poCtrl = new PageOfficeCtrl(request);
                //设置服务页面
                poCtrl.setServerPage(request.getContextPath() + "/poserver.zz");
                //添加自定义保存按钮
                poCtrl.addCustomToolButton("保存", "Save", 1);
                poCtrl.setJsFunction_AfterDocumentSaved("AfterDocumentSaved()");
                //添加自定义盖章按钮
                //poCtrl.addCustomToolButton("盖章", "AddSeal", 2);
                poCtrl.setWriter(doc);

                if(isdic){
                    String AsTmp = fileEnum.getParam();
                    //设置处理文件保存的请求方法
                    poCtrl.setSaveFilePage("/sys/office/save" + (StringUtil.isBlank(AsTmp) ? "" : ("?" + AsTmp)));
                    //打开word
                    poCtrl.webOpen("file://" + AsFileName, OpenModeType.docNormalEdit, "张三");
                }else{
                    String AsTmp = fileEnum.getParam();
                    int indexwz = AsTmp.lastIndexOf("=");
                    String ff = AsTmp.substring(0,indexwz+1)+newfileId;
                    //设置处理文件保存的请求方法
                    poCtrl.setSaveFilePage("/sys/office/save" + (StringUtil.isBlank(ff) ? "" : ("?" + ff)));
                    poCtrl.webOpen("file://" + copypath, OpenModeType.docNormalEdit, "张三");
                }

                map.put("pageoffice", poCtrl.getHtmlCode("PageOfficeCtrl1"));

                return "/office/word";
            } else {
                return "/office/error";
            }

        } catch (
                Exception e) {
            e.printStackTrace();
            request.setAttribute("emsg", e.getMessage());
            return "/office/error";
        }
    }


    public void addStampRecord(FileEnum fileEnum, WordDocument doc,String copypath) throws Exception {
        String fileId = fileEnum.getFileId();
        String filePath = fileEnum.getFilePath();
        SupervisorFile file = supervisorFileService.selectByPrimaryKey(fileId);
        String fileType = file.getType();
        BaseDict dict = DictUtil.getDictByCode(DictTypes.WJ, file.getType());
        String lcTypeStr = dict.getBadtLevel10();
        String lcType = "";
        if (StringUtil.isNotBlank(lcTypeStr)) {
            if (lcTypeStr.indexOf("003") > -1) {
                lcType = "003";
            } else if (lcTypeStr.indexOf("004") > -1) {
                lcType = "004";
            } else if (lcTypeStr.indexOf("005") > -1) {
                lcType = "005";
            }
        } else {
            throw new Exception("获取字典流程类型失败");
        }
        List<AffairCase> caseList = getLcAffair(fileId, lcType);
        if (caseList.size() == 0) {
            throw new Exception("没有查询到流程记录，请确认文件已经审批后再操作");
        }
        String baseConfiId = "";
        switch (lcType) {
            case "005":
                /*承发三签*/
                baseConfiId = "76";
                break;
            case "004":
                /*监发三签*/
                baseConfiId = "74";
                break;
            default:
                /*监发两签*/
                baseConfiId = "75";
                break;
        }
        String roleName = supervisorProjectService.getUserRole(fileId);
        if (StringUtil.isBlank(roleName)) {
            throw new Exception("您没有权限操作");
        } else {
            /*001 审批 002 审核 003 监发两签 004 监发三签  005 承发三签字*/
            if ("xmjl".equals(roleName)) {
             /*   if ("005".equals(lcType)) {
                    throw new Exception("应由承建单位操作");
                }*/
            } else if ("yz".equals(roleName)) {
                throw new Exception("您没有权限操作");
            } else if ("cj".equals(roleName)) {
                if (!"005".equals(lcType)) {
                    throw new Exception("您没有权限操作");
                }
            }

        }
        BasePathConfig basePathConfig = basePathConfigService.selectByPrimaryKey(baseConfiId);
        String templateFile = basePathConfig.getBfcTemplateFile();
        if(FilePathUtil.getFileSufiix(filePath).toLowerCase().equals(".doc")){
            templateFile=templateFile.substring(0,templateFile.lastIndexOf("."))+".doc";
        }
        if(StringUtil.isNotBlank(copypath)){
            // 生成一个 新的报审表文件
            org.apache.commons.io.FileUtils.copyFile(new File(templateFile),new File(copypath));
            filePath=copypath;
        }else{
            WordUtil.mergeWord(filePath, templateFile);
        }


        int leftsetGz = 300;
        int leftsetQz = 320;
        //2.书签插入内容
        /*文件名称*/
        DataRegion filenameSq = doc.openDataRegion("PO_PN");
        filenameSq.setValue(file.getFileName());
        /*审批意见*/
        AffairRecordDTO jlRecord = getSpRecord(caseList, file, "xmjl");
        AffairRecordDTO yzRecord = getSpRecord(caseList, file, "yz");
        AffairRecordDTO cyRecord = getSpRecord(caseList, file, "cj");
        /* String AsbImgs = "[image]file://" + url + "[/image]";*/
        /*文档后面追加 扫描件图片*/
        if (jlRecord != null) {
            if (!"004".equals(lcType) && !"003".equals(lcType)) {
                /*承发三签*/
                DataRegion jlRemarkSq = doc.openDataRegion("PO_JL_R");
                String remark=jlRecord.getRemark();
                if(StringUtil.isNotBlank(remark)){
                    jlRemarkSq.setValue(remark);
                }

            }
            DataRegion jlRemarkDateSq = doc.openDataRegion("PO_JL_DATE");
            String jlOperDate = jlRecord.getOperDate();
            if (jlOperDate != null && StringUtil.isNotBlank(jlOperDate)) {
                String datestr = com.qili.util.DateUtil.parseDateStrByFormat(jlOperDate, "yyyy年MM月dd日 HH时mm分");
                jlRemarkDateSq.setValue(datestr);
            }
            /*插入签名*/
            String xmjlImageQzUrl = getImageByUserAndType("203", jlRecord.getOperUserId());
            if (StringUtil.isNotBlank(xmjlImageQzUrl)) {
                WordUtil.addStampImageTable(filePath, filePath, "", xmjlImageQzUrl, "&签字", "监理单位代表", false, true, leftsetGz, leftsetQz, "");
            }

        }
        if (yzRecord != null) {
            DataRegion yzRemarkSq = doc.openDataRegion("PO_YZ_R");
            if(StringUtil.isNotBlank(yzRecord.getRemark())){
                yzRemarkSq.setValue(yzRecord.getRemark());
            }
            DataRegion yzRemarkDateSq = doc.openDataRegion("PO_YZ_DATE");
            String yzoperDate = yzRecord.getOperDate();
            if (yzoperDate != null && StringUtil.isNotBlank(yzoperDate)) {
                String datestr = com.qili.util.DateUtil.parseDateStrByFormat(yzoperDate, "yyyy年MM月dd日 HH时mm分");
                yzRemarkDateSq.setValue(datestr);
            }
            /*插入签名*/
            String yzImageQzUrl = getImageByUserAndType("203", yzRecord.getOperUserId());
            if (StringUtil.isNotBlank(yzImageQzUrl)) {
                WordUtil.addStampImageTable(filePath, filePath, "", yzImageQzUrl, "&签字", "业主单位代表", false, true, leftsetGz, leftsetQz, "");
            }
        }
        if (cyRecord != null) {
            if (!"003".equals(lcType)) {
                /* 监发三签 承发三签*/
                if ("004".equals(lcType)) {
                    /*监发三签*/
                    DataRegion cjRemarkSq = doc.openDataRegion("PO_CJ_R");
                    if(StringUtil.isNotBlank(cyRecord.getRemark())){
                        cjRemarkSq.setValue(cyRecord.getRemark());
                    }

                }
                DataRegion cjRemarkDateSq = doc.openDataRegion("PO_CJ_DATE");
                String cjoperDate = cyRecord.getOperDate();
                if (cjoperDate != null && StringUtil.isNotBlank(cjoperDate)) {
                    String datestr = com.qili.util.DateUtil.parseDateStrByFormat(cjoperDate, "yyyy年MM月dd日 HH时mm分");
                    cjRemarkDateSq.setValue(datestr);
                }
                /*插入签名*/
                String cjImageQzUrl = getImageByUserAndType("203", cyRecord.getOperUserId());
                if (StringUtil.isNotBlank(cjImageQzUrl)) {
                    WordUtil.addStampImageTable(filePath, filePath, "", cjImageQzUrl, "&签字", "承建单位代表", false, true, leftsetGz, leftsetQz, "");
                }
            }

        }

        // 20210811 报审表插入后，记录一下。已经插入的，页面上有提示
        file.setBsStatus("1");
        supervisorFileService.updateByPrimaryKey(file);

    }


    /**
     * @param file
     * @param roleName
     * @Author:zhaoyongke
     * @Description: 根据角色获取审批意见
     * @Date:16:12 2021/2/1
     */
    public AffairRecordDTO getSpRecord(List<AffairCase> affairCases, SupervisorFile file, String roleName) {
        AffairRecordDTO recorddto = null;
        String caseId = affairCases.get(0).getCaseId();
        SupervisorProject project = supervisorProjectService.selectByPrimaryKey(file.getProjectId());
        //  查询流程审批意见
        if ("xmjl".equals(roleName)) {
            //项目经理
            String projectManagerPerson = project.getProjectManagerPerson();
            //
            recorddto = affairRecordService.getReamrKByOper(caseId, projectManagerPerson);
        } else if ("yz".equals(roleName)) {
            //业主
            ProjectLeader projectLeader = new ProjectLeader();
            projectLeader.setSupervisorProjectId(project.getId());
            List<ProjectLeader> leaderList = projectLeaderService.select(projectLeader);
            if (leaderList.size() > 0) {
                for (int i = 0; i < leaderList.size(); i++) {
                    String projectLeaderUserId = leaderList.get(i).getProjectLeader();
                    recorddto = affairRecordService.getReamrKByOper(caseId, projectLeaderUserId);
                    if (recorddto != null) {
                        break;
                    }
                }
            }
        } else if ("cj".equals(roleName)) {
            ProjectUnitConstruction projectUnitConstruction = new ProjectUnitConstruction();
            projectUnitConstruction.setSupervisorProjectId(project.getId());
            List<ProjectUnitConstruction> selectcj = projectUnitConstructionService.select(projectUnitConstruction);
            if (selectcj.size() > 0) {
                for (int i = 0; i < selectcj.size(); i++) {
                    String projectManager = selectcj.get(i).getProjectManager();
                    recorddto = affairRecordService.getReamrKByOper(caseId, projectManager);
                    if (recorddto != null) {
                        break;
                    }
                }
            }
        }
        return recorddto;

    }


    /**
     * @param lcType
     * @Author:zhaoyongke
     * @Description: 获取流程事项
     * @Date:16:19 2021/2/1
     */
    public List<AffairCase> getLcAffair(String fileId, String lcType) {
        Example example = new Example(AffairCase.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("businessId", fileId);
        criteria.andEqualTo("lcType", lcType);
        example.setOrderByClause("accept_time  desc ");
        List<AffairCase> affairCases = affairCaseService.selectByExample(example);
        return affairCases;
    }

    /**
     * @param fileEnum
     * @param doc
     * @Author:zhaoyongke
     * @Description: 盖章操作
     * @Date:16:52 2021/1/14
     */
    public void addStamp(FileEnum fileEnum, WordDocument doc) throws Exception {
        /*获取的文件的生成方式  1 表单模板 0 上传文件方式 */
        String fileId = fileEnum.getFileId();
        String filePath = fileEnum.getFilePath();
        /*获取文件生成方式*/
        String createFlag = getWjCreate(fileId);
        /*获取当前用户的角色*/
        String roleName = supervisorProjectService.getUserRole(fileId);
        /*获取文件--签字 盖章 操作*/
        HashMap mapoper = supervisorFileService.getOperByRole(roleName, fileId);
        if (StringUtil.isBlank(roleName)) {
            throw new Exception("您没有权限签字盖章");
        }
        // 根据角色获取承建和监理签章图片
        JSONObject objectImage = getQzUrlBySf(roleName, fileId);
        SupervisorFile file = supervisorFileService.selectByPrimaryKey(fileId);
        String filetype = file.getType();
        /*直接上传生成的文档  搜索关键字（签章）插入图片*/
        /*文档搜索关键字 并且含有（盖章）*/
        String oper = "";
        String context = "";
        if (mapoper.get("oper") != null) {
            oper = mapoper.get("oper").toString();
        }
        if (mapoper.get("keyword") != null) {
            context = mapoper.get("keyword").toString();
        }
        /*ta表格的形式盖章 w 文档中非表格位置的搜索盖章  */
        /*签章图片*/
        String imageGzUrl = objectImage.get("gz") + "";
        String imageQzUrl = objectImage.get("qz") + "";
        int leftsetGz = 300;
        int leftsetQz = 300;
        // 项目经理用章标志
        Boolean  userTamp=false;
        if (StringUtil.isNotBlank(oper)) {
            switch (oper) {
                case "1a":
                    if (StringUtil.isBlank(imageQzUrl) || "null".equals(imageQzUrl)) {
                        throw new Exception("请在个人中心上传签字图片");
                    }
                    /*只是需要签字的 第一种形式(右上角 文字替换)*/
                    WordUtil.addStampImageTableClearQz(filePath, filePath, imageQzUrl, imageQzUrl, context, false, true);
                    break;
                case "2a":
                    if (StringUtil.isBlank(imageGzUrl) || "null".equals(imageGzUrl)) {
                        if("xmjl".equals(roleName)){
                            throw new Exception("请在监理项目用章授权书中选择签章图片");
                        }else{
                            throw new Exception("请维护签章图片");
                        }
                    }
                    /*只是需要盖章 第一种形式（盖章到封面）*/
                    context = "山东正中信息技术股份有限公司";
                    int left=170;
                    int top=-40;
                    if ("008".equals(filetype)){
                        /*监理工作规范*/
                         left=135;
                         top=-40;
                    }
                    WordUtil.addStampBykeyWord(filePath, filePath, imageGzUrl, context,left,top);
                    userTamp=true;
                    break;
                case "3a":
                    /*盖章和签字 分开*/
                    if (StringUtil.isBlank(imageQzUrl) || "null".equals(imageQzUrl)) {
                        throw new Exception("请在个人中心上传签字图片");
                    }
                    //签字
                    WordUtil.addStampImageTableClearQz(filePath, filePath, imageQzUrl, imageQzUrl, context, false, true);
                    // 盖章
                    context = "山东正中信息技术股份有限公司";
                    if (StringUtil.isBlank(imageGzUrl) || "null".equals(imageGzUrl)) {
                        if("xmjl".equals(roleName)){
                            throw new Exception("请在监理项目用章授权书中选择签章图片");
                        }else{
                            throw new Exception("请维护签章图片");
                        }

                    }
                    WordUtil.addStampBykeyWord(filePath, filePath, imageGzUrl, context,170,-40);
                    userTamp=true;
                    break;
                case "4a":
                    /*盖章和签字 合并*/
                    if (StringUtil.isBlank(imageQzUrl) || "null".equals(imageQzUrl)) {
                        throw new Exception("请在个人中心上传签字图片");
                    }
                    if (!"zjl".equals(roleName)) {
                        /*总监理没有章*/
                        if (StringUtil.isBlank(imageGzUrl) || "null".equals(imageGzUrl)) {
                            if("xmjl".equals(roleName)){
                                throw new Exception("请在监理项目用章授权书中选择签章图片");
                            }else{
                                throw new Exception("请维护签章图片");
                            }

                        }
                    }
                    if ("073".equals(filetype) || "074".equals(filetype) || "046".equals(filetype) || "016".equals(filetype) || "010".equals(filetype) || "098".equals(filetype) || "045".equals(filetype) || "055".equals(filetype) || "061".equals(filetype) || "081".equals(filetype) || "062".equals(filetype) || "063".equals(filetype)) {
                        /*  073检验报告 074 检测报告   046 隐蔽验收报告 由于是 表格 3列   开工通知两列 016   工程备忘表 098 3列*/
                        /*081  061  055  验收报告   062 承建工程移交单*/
                        leftsetGz = 10;
                        leftsetQz = 10;
                    }

                    if("111".equals(filetype)){
                        leftsetGz = 250;
                        leftsetQz = 250;
                    }
                    if ("093".equals(filetype)) {
                        /*工程变更单 监理工程师 盖项目经理的章*/
                        if ("zjl".equals(roleName)) {
                            JSONObject zjlImage = getQzUrlBySf("xmjl", fileId);
                            imageGzUrl = zjlImage.get("gz") + "";
                            if (StringUtil.isBlank(imageGzUrl) || "null".equals(imageGzUrl)) {
                                //throw new Exception("项目经理没有上传签章图片");
                                throw new Exception("请在监理项目用章授权书中选择签章图片");
                            }

                        }
                    }
                    if("xmjl".equals(roleName)){
                        userTamp=true;
                    }
                    WordUtil.addStampImageTable(filePath, filePath, imageGzUrl, imageQzUrl, "&章", context, true, true, leftsetGz, leftsetQz, "");
                    break;
                case "5a":
                    /*  针对业主单位盖章签字：盖章位置 只是签字 ,盖章由项目经理上传图片   如 业主单位 */
                    if (StringUtil.isBlank(imageQzUrl) || "null".equals(imageQzUrl)) {
                        throw new Exception("请在个人中心上传签字图片");
                    }
                    if ("073".equals(filetype) || "074".equals(filetype) || "046".equals(filetype) || "016".equals(filetype) || "010".equals(filetype) || "098".equals(filetype) || "045".equals(filetype) || "055".equals(filetype) || "061".equals(filetype) || "081".equals(filetype) || "062".equals(filetype) || "063".equals(filetype) || "091".equals(filetype))  {
                        /*检验报告  由于是 表格   3列   开工通知两列 016   045 到货验收报告*/
                        /*081  061  055  验收报告  062 承建工程移交单*/
                        leftsetGz = 10;
                        leftsetQz = 10;
                    }
                    if("111".equals(filetype)){
                        /*监理通知*/
                        leftsetGz = 250;
                        leftsetQz = 250;
                    }
                    WordUtil.addStampImageTable(filePath, filePath, imageGzUrl, imageQzUrl, "&章", context, false, true, leftsetGz, leftsetQz, "");
                    break;
                case "6a":
                    /*  表格中只是签字  052工程初验报审表   059工程终验报审表  077服务验收报审表    */
                    if (StringUtil.isBlank(imageQzUrl) || "null".equals(imageQzUrl)) {
                        throw new Exception("请在个人中心上传签字图片");
                    }
                    String keyword = "&章";
                    if ("zjl".equals(roleName)) {
                        if ("088".equals(filetype) || "109".equals(filetype) ||  "089".equals(filetype) ||   "110".equals(filetype) ) {
                            /*监理付款申请   089 支付意见*/
                            keyword = "&签字";
                        }
                    }
                    if ("082".equals(filetype)  ||  "075".equals(filetype) ||  "076".equals(filetype) ||  "084".equals(filetype)   ) {
                        /*验收会议纪要082 初验会议纪要075  终验会议纪要076  其他监理工作--项目会议084 */
                        leftsetGz = 10;
                        leftsetQz = 10;
                    }
                    if("039".equals(filetype)  || "040".equals(filetype)   || "041".equals(filetype)  || "091".equals(filetype)  ){
                        /*设备进场检验报告039 开箱检验报告040*/
                        keyword = "&签字";
                        leftsetGz = 10;
                        leftsetQz = 10;
                    }
                    if ("036".equals(filetype) || "037".equals(filetype) || "106".equals(filetype) || "086".equals(filetype) || "100".equals(filetype)) {
                        /*检查旁站   086 监理周报  100  监理日志*/
                        keyword = "&签字";
                    }
                    WordUtil.addStampImageTable(filePath, filePath, imageGzUrl, imageQzUrl, keyword, context, false, true, leftsetGz, leftsetQz, filetype);
                    break;
                case "7a":
                    /*  监理付款申请   项目经理只是盖章   */
                    if (StringUtil.isBlank(imageGzUrl) || "null".equals(imageGzUrl)) {
                        throw new Exception("请维护签章图片");
                    }
                    if("091".equals(filetype)){
                        /*监理通知*/
                        leftsetGz = 10;
                        leftsetQz = 10;
                    }
                    if("xmjl".equals(roleName)){
                        userTamp=true;
                    }
                    if( "089".equals(filetype) || "110".equals(filetype)  || "091".equals(filetype) ||  "109".equals(filetype) ||  "088".equals(filetype)  ){
                        WordUtil.addStampImageTable(filePath, filePath, imageGzUrl, imageQzUrl, "&章", context, true, false, leftsetGz, leftsetQz, filetype);
                    }else{
                        WordUtil.addStampImageTable(filePath, filePath, imageGzUrl, imageQzUrl, "&章", context, true, false, leftsetGz, leftsetQz, "");
                    }

                    break;
                default:
                    break;
            }

            if(userTamp){
                /*保存项目经理用章记录*/
                projectSealRecordService.saveSealRecord(file);
            }
        } else {
            throw new Exception("您没有权限操作！");
        }

    }

    /**
     * @param roleName
     * @param type
     * @Author:zhaoyongke
     * @Description: 根据流程类型和角色获取搜索关键字
     * @Date:11:26 2021/1/16
     */
    public String getContextByLcType(String roleName, String type) {
        String context = "";
        BaseDict baseDict = DictUtil.getDictByCode(DictTypes.WJ, type);
        String lctypecode = baseDict.getBadtLevel10();
        if (StringUtil.isNotBlank(lctypecode)) {
            lctypecode = lctypecode + "";
            String lctype = "";
            if (lctypecode.indexOf("003") > 0) {
                /*监发两签*/
                lctype = "003";
            } else if (lctypecode.indexOf("004") > 0) {
                /*监发三签*/
                lctype = "004";
            } else if (lctypecode.indexOf("005") > 0) {
                /*承发三签*/
                lctype = "005";
            } else if (lctypecode.indexOf("001") > 0) {
                /*审批*/
                lctype = "001";
            } else if (lctypecode.indexOf("002") > 0) {
                /*审核*/
                lctype = "002";
            } else {
                lctype = "";
            }
            if (StringUtil.isNotBlank(lctype)) {
                //监发两签
                BaseDict baseDictlc = DictUtil.getDictByCode(DictTypes.LCTYPE, lctype);
                if ("jl".equals(roleName)) {
                    context = baseDictlc.getBadtLevel1();
                } else if ("cj".equals(roleName)) {
                    context = baseDictlc.getBadtLevel3();
                } else if ("yz".equals(roleName)) {
                    context = baseDictlc.getBadtLevel2();
                }
            }
        }

        return context;
    }


    /**
     * @param fileId
     * @Author:zhaoyongke
     * @Description: 获取文件的上传方式
     * @Date:16:23 2021/1/14
     */
    public String getWjCreate(String fileId) {
        SupervisorFile file = supervisorFileService.selectByPrimaryKey(fileId);
        String type = file.getType();
        BaseDict base = DictUtil.getDictByCode(DictTypes.WJ, type);
        /*获取的文件的生成方式  1 表单模板 0 上传文件方式 */
        String level8 = base.getBadtLevel8();
        String flag = "";
        if ("1".equals(level8)) {
            /*表单生成*/
            flag = "1";
        } else {
            /*上传文件*/
            flag = "0";
        }
        return flag;
    }



    /**
     * @param sfname
     * @Author:zhaoyongke
     * @Description: 根据不同身份返回签章的rul
     * @Date:11:19 2020/12/16
     */
    public JSONObject getQzUrlBySf(String sfname,String fileId) {
        JSONObject object=new JSONObject();
        String url = "";

        // 电子签章  202
        if ("xmjl".equals(sfname) || "zjl".equals(sfname) || "cj".equals(sfname)  || "jsfzr".equals(sfname)  ) {
            /*签章图片*/
            // 20210911  监理的盖章图片从项目授权书中获取  只针对监理
            String gzIamge ="";
            if(!"cj".equals(sfname) ){
                //
                SupervisorFile  file=supervisorFileService.selectByPrimaryKey(fileId);
                String projectId = file.getProjectId();
                // 获取项目授权书
                SupervisorFileDTO fileSeal=new SupervisorFileDTO();
                fileSeal.setProjectId(projectId);
                List<SupervisorFileDTO> supervisorFileDTOS = supervisorFileService.queryFileSealUrl(fileSeal);
                if(supervisorFileDTOS!=null){
                    if(supervisorFileDTOS.size()>0){
                        gzIamge=supervisorFileDTOS.get(0).getUrl();
                    }
                }
//                if(StringUtil.isBlank(gzIamge)){
//                    // 如果授权书书里的签章没有获取，则 获取个人中心的
//                    gzIamge = getImageByType("202");
//                }
            }
            else{
                 gzIamge = getImageByType("202");
            }



            String qzIamge = getImageByType("203");
            /*盖章图片*/
            object.put("gz", gzIamge);
            /*签字图片*/
            object.put("qz", qzIamge);
        } else if ("yz".equals(sfname)) {
            //查询文件下面的
            SupervisorFile file = new SupervisorFile();
            file.setParentId(fileId);
            file.setType("113");
            List<SupervisorFile> fileList = supervisorFileService.select(file);
            if (fileList.size() > 0) {
                url = fileList.get(0).getUrl();
            }
            /*盖章图片*/
            object.put("gz", url);
            String qzIamge = getImageByType("203");
            /*签字图片*/
            object.put("qz", qzIamge);
        }
        return object;
    }
    /**
    * @Author:zhaoyongke
    * @Description:
    * @param type
    * @Date:16:49 2021/1/27
    */
    public  String  getImageByType(String type){
        String url="";
        String userId = CommonUtil.getUserId();
        SupervisorFile file = new SupervisorFile();
        file.setProjectId(userId);
        file.setType(type);
        SupervisorFile supervisorFile = supervisorFileService.selectOne(file);
        if (supervisorFile != null) {
            url = supervisorFile.getUrl();
        }
        return  url;
    }
    /**
    * @Author:zhaoyongke
    * @Description:
    * @param type
    * @param userId
    * @Date:10:11 2021/2/2
    */
    public  String  getImageByUserAndType(String type,String userId){
        String url="";
        SupervisorFile file = new SupervisorFile();
        file.setProjectId(userId);
        file.setType(type);
        SupervisorFile supervisorFile = supervisorFileService.selectOne(file);
        if (supervisorFile != null) {
            url = supervisorFile.getUrl();
        }
        return  url;
    }

    /**
     *
     * @Author:zhaoyongke
     * @Description: 签字：查询图片url
     * @Date:10:05 2020/12/29
     */
    public JSONObject getTagAndUrlSign() {
        JSONObject object = new JSONObject();
        String tag = "";
        // 当前登录人Id
        String userId = CommonUtil.getUserId();
        SupervisorFile file = new SupervisorFile();
        file.setProjectId(userId);
        /*电子签名*/
        file.setType("203");
        SupervisorFile supervisorFile = supervisorFileService.selectOne(file);
        String  url="";
        if (supervisorFile != null) {
            url = supervisorFile.getUrl();
        }
        object.put("tag", "PO_SIGN");
        object.put("url", url);
        return object;
    }

    /**
     * @param request
     * @param map
     * @Author:Zhangshuo
     * @Description:
     * @Date:21:12 2020/11/14
     */
    public String openWordForProjectById(HttpServletRequest request, Map<String, Object> map, FileEnum fileEnum) {
        try {
            //根据参数获取实体类
            SupervisorProjectForms supervisorProjectForms = supervisorProjectFormsService.selectByPrimaryKey(fileEnum.getFileFormId());
            SupervisorProjectFormsData fromdata = new SupervisorProjectFormsData();
            // 根据 from 表主键 查询formdata
            fromdata.setSpfId(supervisorProjectForms.getSpfId());

            List<SupervisorProjectFormsData> listTableData = supervisorProjectFormsDataService.select(fromdata);

            BasePathConfig basePathConfig = basePathConfigService.selectByPrimaryKey(fileEnum.getFilePathId());
            if (!isNull(supervisorProjectForms) && (!isNull(basePathConfig))) {
                //需要打开的文件名
                String AsFileName = basePathConfig.getBfcTemplateFile();
                if(StringUtils.isNotBlank(request.getParameter("fbCode"))){
                    AsFileName = FilePathUtil.getPackageTemplate(AsFileName,request.getParameter("fbCode"));
                }
                if (StringUtil.isNotBlank(AsFileName)) {
                    WordDocument doc = new WordDocument();
                    PageOfficeCtrl poCtrl;
                    try {
                        //禁用右击事件
                        doc.setDisableWindowRightClick(true);
                        //加载Region
                        loadRegion(doc, supervisorProjectForms, listTableData);
                        //初始化PageOfficeCtrl
                        poCtrl = new PageOfficeCtrl(request);
                        //设置服务页面
                        poCtrl.setServerPage(request.getContextPath() + "/poserver.zz");
                        //添加自定义保存按钮
                        poCtrl.addCustomToolButton("保存", "Save", 1);
                        poCtrl.setJsFunction_AfterDocumentSaved("AfterDocumentSaved()");
                        //添加自定义盖章按钮
                        //poCtrl.addCustomToolButton("盖章", "AddSeal", 2);
                        poCtrl.setWriter(doc);
                        String AsTmp = fileEnum.getParam();
                        //设置处理文件保存的请求方法
                        poCtrl.setSaveFilePage("/sys/office/save" + (StringUtil.isBlank(AsTmp) ? "" : ("?" + AsTmp)));

                        //打开word
                        poCtrl.webOpen("file://" + AsFileName, OpenModeType.docNormalEdit, "张三");
                        map.put("pageoffice", poCtrl.getHtmlCode("PageOfficeCtrl1"));
                    } finally {
                        // doc.
                    }
                    return "/office/word";
                } else {
                    return "/office/error";
                }
            } else {
                return "/office/error";
            }
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("emsg", e.getMessage());
            return "/office/error";
        }
    }

    /**
     * @param request
     * @param map
     * @Author:Zhangshuo
     * @Description:
     * @Date:21:12 2020/11/14
     */
    public String openWordOnly(HttpServletRequest request, Map<String, Object> map, FileEnum fileEnum) {
        try {
            //文件路径
            String AsFileName = fileEnum.getFilePath();
            if (StringUtil.isNotBlank(AsFileName)) {
                //初始化PageOfficeCtrl
                PageOfficeCtrl poCtrl = new PageOfficeCtrl(request);
                poCtrl.setOfficeVendor(OfficeVendorType.AutoSelect);
                //设置服务页面
                poCtrl.setServerPage(request.getContextPath() + "/poserver.zz");
                //添加自定义保存按钮
                //poCtrl.addCustomToolButton("保存", "Save", 1);
                // poCtrl.setJsFunction_AfterDocumentSaved("AfterDocumentSaved()");
                //添加自定义盖章按钮
                // poCtrl.addCustomToolButton("盖章", "AddSeal", 2);
                String AsTmp = fileEnum.getParam();
                //设置处理文件保存的请求方法
                //poCtrl.setSaveFilePage("/sys/office/save" + (StringUtil.isBlank(AsTmp) ? "" : ("?" + AsTmp)));
                //AsFileName = "file://" + "/www/server/jar/cc/产品信息库/合同/监理合同_001_20201214_项目名称21.doc";

                String fileType = getFileType(fileEnum.getFilePath());
                OpenModeType modeltype = OpenModeType.docReadOnly;
                if ("word".equals(fileType)) {
                    modeltype = OpenModeType.docReadOnly;
                } else if ("excel".equals(fileType)) {
                    modeltype = OpenModeType.xlsReadOnly;
                } else if ("ppt".equals(fileType)) {
                    modeltype = OpenModeType.pptReadOnly;
                }

                if("pdf".equals(fileType)){
                    PDFCtrl poCtrl1 = new PDFCtrl(request);
                    poCtrl1.setMenubar(false);
                    poCtrl1.setServerPage(request.getContextPath() + "/poserver.zz");
                    openPdf(poCtrl1,AsFileName);
                    map.put("pageoffice", poCtrl1.getHtmlCode("PageOfficeCtrl1"));
                    return "/office/pagepdf";
                }else{
                    poCtrl.setMenubar(false);
                    //打开word
                    poCtrl.webOpen("file://" + AsFileName, modeltype, "张三");
                    map.put("pageoffice", poCtrl.getHtmlCode("PageOfficeCtrl1"));
                    return "/office/word";
                }

            } else {
                return "/office/error";
            }
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("emsg", e.getMessage());
            return "/office/error";
        }
    }

    /**
     * @param request
     * @param map
     * @param fileEnum
     * @Author:zhaoyongke
     * @Description:
     * @Date:14:28 2021/1/6
     */
    public String openWordEdit(HttpServletRequest request, Map<String, Object> map, FileEnum fileEnum) {
        try {
            //文件路径
            String AsFileName = fileEnum.getFilePath();
            String fileId = fileEnum.getFileId();
            if (StringUtil.isNotBlank(AsFileName)) {
                //初始化PageOfficeCtrl
                PageOfficeCtrl poCtrl = new PageOfficeCtrl(request);
                poCtrl.setOfficeVendor(OfficeVendorType.AutoSelect);
                //设置服务页面
                poCtrl.setServerPage(request.getContextPath() + "/poserver.zz");

                poCtrl.setJsFunction_AfterDocumentSaved("AfterDocumentSaved()");
                //添加自定义盖章按钮
                // poCtrl.addCustomToolButton("盖章", "AddSeal", 2);
                String AsTmp = fileEnum.getParam();
                //设置处理文件保存的请求方法
                poCtrl.setSaveFilePage("/sys/office/save" + (StringUtil.isBlank(AsTmp) ? "" : ("?" + AsTmp)));
                //AsFileName = "file://" + "/www/server/jar/cc/产品信息库/合同/监理合同_001_20201214_项目名称21.doc";
                String fileType = getFileType(fileEnum.getFilePath());

                SupervisorFile  supervisorFile=supervisorFileService.selectByPrimaryKey(fileId);
                String type=supervisorFile.getType();
                String projectId=supervisorFile.getProjectId();
                String role=sysUserService.getUserRole(projectId);
                Boolean  isedit=true;
                if("xmjl".equals(role) || "cj".equals(role)  || "zjlgcs".equals(role) ) {
                    if ("cj".equals(role)) {
                        BaseDict wjdict = DictUtil.getDictByCode(DictTypes.WJ, type);
                        String level13 = wjdict.getBadtLevel13();
                        if(StringUtil.isBlank(level13)  || level13.indexOf("cj") < 0 ){
                            isedit=false;
                        }
                    }
                }else{
                    isedit=false;
                }
                String createType = supervisorFile.getCreateType();
                OpenModeType modeltype = OpenModeType.docReadOnly;
                if(isedit){
                    if ("word".equals(fileType)) {
                        modeltype = OpenModeType.docNormalEdit;
                    } else if ("excel".equals(fileType)) {
                        modeltype = OpenModeType.xlsNormalEdit;
                    } else if ("ppt".equals(fileType)) {
                        modeltype = OpenModeType.pptNormalEdit;
                    }
                    if(!"1".equals(createType)){
                        //添加自定义保存按钮
                        poCtrl.addCustomToolButton("保存", "Save", 1);
                    }
                }else{
                    if ("word".equals(fileType)) {
                        modeltype = OpenModeType.docReadOnly;
                    } else if ("excel".equals(fileType)) {
                        modeltype = OpenModeType.xlsReadOnly;
                    } else if ("ppt".equals(fileType)) {
                        modeltype = OpenModeType.pptReadOnly;
                    }
                }
                if("pdf".equals(fileType)){
                    PDFCtrl poCtrl1 = new PDFCtrl(request);
                    poCtrl1.setServerPage(request.getContextPath() + "/poserver.zz");
                    openPdf(poCtrl1,AsFileName);
                    map.put("pageoffice", poCtrl1.getHtmlCode("PageOfficeCtrl1"));
                    return "/office/pagepdf";
                }else{
                    //打开word
                    poCtrl.webOpen("file://" + AsFileName, modeltype, "张三");
                    map.put("pageoffice", poCtrl.getHtmlCode("PageOfficeCtrl1"));
                    return "/office/word";
                }

            } else {
                return "/office/error";
            }
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("emsg", e.getMessage());
            return "/office/error";
        }
    }
   /**
   * @Author:zhaoyongke
   * @Description:
    * @param AsFileName
   * @Date:15:56 2021/3/19
   */
    public  void openPdf(PDFCtrl poCtrl1,String AsFileName){
//        poCtrl1.addCustomToolButton("打印", "Print()", 6);
        poCtrl1.addCustomToolButton("-", "", 0);
        poCtrl1.addCustomToolButton("实际大小", "SetPageReal()", 16);
        poCtrl1.addCustomToolButton("适合页面", "SetPageFit()", 17);
        poCtrl1.addCustomToolButton("适合宽度", "SetPageWidth()", 18);
        poCtrl1.addCustomToolButton("-", "", 0);
        poCtrl1.addCustomToolButton("旋转", "RotateLeft()", 12);
        poCtrl1.addCustomToolButton("旋转", "RotateRight()", 13);
        poCtrl1.addCustomToolButton("放大", "openBig()", 14);
        poCtrl1.addCustomToolButton("缩小", "openLit()", 15);
        poCtrl1.addCustomToolButton("-", "", 0);
        poCtrl1.addCustomToolButton("首页", "FirstPage()", 8);
        poCtrl1.addCustomToolButton("上一页", "PreviousPage()", 9);
        poCtrl1.addCustomToolButton("下一页", "NextPage()", 10);
        poCtrl1.addCustomToolButton("尾页", "LastPage()", 11);
        poCtrl1.addCustomToolButton("-", "", 0);
        //document.getElementById("PDFCtrl1").ZoomIn();

 /*       document.getElementById("PDFCtrl1").FullScreen = true|false;*/
        poCtrl1.webOpen("file://" + AsFileName);
    }

    /**
     * @param filePath
     * @Author:zhaoyongke
     * @Description:获取文件类型
     * @Date:14:34 2021/1/6
     */
    public String getFileType(String filePath) {
        String AsSuffix = FilePathUtil.getFileSufiix(filePath).toLowerCase();
        String type = "word";
        switch (AsSuffix) {
            case ".doc":
                type = "word";
                break;
            case ".docx":
                type = "word";
                break;
            case ".xls":
                type = "excel";
                break;
            case ".xlsx":
                type = "excel";
                break;
            case ".ppt":
                type = "ppt";
                break;
            case ".pptx":
                type = "ppt";
                break;
            case ".pdf":
                type = "pdf";
                break;
            default:
                type = "word";
        }
        return type;

    }

    /**
     * @param request
     * @Author:Zhangshuo
     * @Description:根据传递参数获取Form实体类
     * @Date:11:43 2020/11/16
     */
    public FileEnum getRequestParam(HttpServletRequest request) {
        String AsTmp = request.getParameter("ft");
        int AiFt = Integer.valueOf(AsTmp).intValue();
        FileEnum AfTmp = FileEnum.getEnumByType(AiFt);
        if (!isNull(AfTmp)) {
            AsTmp = request.getParameter("fp");
            if (StringUtil.isNotBlank(AsTmp)) {
                try {
                    AsTmp = URLDecoder.decode(AsTmp, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                AfTmp.setFilePath(AsTmp);
            }
            //supervisor_file 表ID 插入图片时的parentid
            AsTmp = request.getParameter("fid");
            if (StringUtil.isNotBlank(AsTmp)) {
                SupervisorFile AoTmp = supervisorFileService.selectByPrimaryKey(AsTmp);
                if (!isNull(AoTmp)) {
                    AfTmp.setFilePath(AoTmp.getUrl());
                    AfTmp.setFileId(AsTmp);
                }
            }
            //supervisor_forms 表ID
            AsTmp = request.getParameter("fmid");
            if (StringUtil.isNotBlank(AsTmp)) {
                AfTmp.setFileFormId(AsTmp);
            }
            //base_pathconfig 表ID 和
            AsTmp = request.getParameter("fpid");
            if (StringUtil.isNotBlank(AsTmp)) {
                AfTmp.setFilePathId(AsTmp);
            }
            AsTmp = request.getParameter("ftg");
            if (StringUtil.isNotBlank(AsTmp)) {
                AfTmp.setFileTag(AsTmp);
            }
            AsTmp = request.getQueryString();
            if (StringUtil.isNotBlank(AsTmp)) {
                AfTmp.setParam(AsTmp);
            }
            return AfTmp;
        } else {
            return null;
        }
    }

    /**
     * @param request
     * @Author:Zhangshuo
     * @Description:根据传递参数获取Form实体类
     * @Date:11:43 2020/11/16
     */
    public FileEnum getRequestParamTemp(HttpServletRequest request) {
        String AsTmp = request.getParameter("ft");
        int AiFt = Integer.valueOf(AsTmp).intValue();
        FileEnum AfTmp = FileEnum.getEnumByType(AiFt);
        if (!isNull(AfTmp)) {
            AsTmp = request.getParameter("fp");
            if (StringUtil.isNotBlank(AsTmp)) {
                try {
                    AsTmp = URLDecoder.decode(AsTmp, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                AfTmp.setFilePath(AsTmp);
            }
            //supervisor_file 表ID 插入图片时的parentid
            AsTmp = request.getParameter("fid");
            if (StringUtil.isNotBlank(AsTmp)) {
                SupervisorFileTemp AoTmp = supervisorFileTempService.selectByPrimaryKey(AsTmp);
                if (!isNull(AoTmp)) {
                    AfTmp.setFilePath(AoTmp.getUrl());
                    AfTmp.setFileId(AsTmp);
                }
            }
            //supervisor_forms 表ID
            AsTmp = request.getParameter("fmid");
            if (StringUtil.isNotBlank(AsTmp)) {
                AfTmp.setFileFormId(AsTmp);
            }
            //base_pathconfig 表ID 和
            AsTmp = request.getParameter("fpid");
            if (StringUtil.isNotBlank(AsTmp)) {
                AfTmp.setFilePathId(AsTmp);
            }
            AsTmp = request.getParameter("ftg");
            if (StringUtil.isNotBlank(AsTmp)) {
                AfTmp.setFileTag(AsTmp);
            }
            AsTmp = request.getQueryString();
            if (StringUtil.isNotBlank(AsTmp)) {
                AfTmp.setParam(AsTmp);
            }
            return AfTmp;
        } else {
            return null;
        }
    }

    /**
     * @param psFileFormId
     * @Author:Zhangshuo
     * @Description:根据传递参数获取Form实体类
     * @Date:11:43 2020/11/16
     */
    public SupervisorProjectForms getProjectFormsByFileFormId(String psFileFormId) {
//        SupervisorProjectFromsDTO supervisorProjectFroms = new SupervisorProjectFromsDTO();
//        supervisorProjectFroms.setSpfId(psFileFormId);
//        supervisorProjectFroms = supervisorProjectFormsService.getFormsDataById(supervisorProjectFroms);
        SupervisorProjectForms supervisorProjectFroms = supervisorProjectFormsService.selectByPrimaryKey(psFileFormId);
        return supervisorProjectFroms;
    }

    /**
     * @param request
     * @param response
     * @Author:Zhangshuo
     * @Description:文件保存
     * @Date:21:12 2020/11/14
     */
    @RequestMapping("/save")
    public void saveFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
        FileEnum fileEnum = getRequestParam(request);
        String fileId=fileEnum.getFileId();
        String AsSavePath = "";
        String AsFileType = "";
        String AsPrjId = "";
        String AsStageId = "";
        String AsMilePostId = "";
        String AsPkgId = "";
        String AsParentId = "";
        String AsLinkId = "";
        String AsWjNum = "";
        String AsFileId = "";
        Integer fileInd = 0;
        String  fbcode = "";
        Boolean AbSaveFlag = false;
        Boolean AbLcStatusFlag = false;
        Boolean AbSealFlag = false;
        SupervisorProjectForms supervisorProjectForms = null;
        switch (fileEnum) {
            case FL_ONLY:
                AsSavePath = fileEnum.getFilePath();
                break;
            case FL_FORMS:
                supervisorProjectForms = supervisorProjectFormsService.selectByPrimaryKey(fileEnum.getFileFormId());
                AsSavePath = supervisorProjectForms.getSaveFilePath();
                AsFileType = supervisorProjectForms.getSpfFilecode();
                AsPrjId = supervisorProjectForms.getSpfPrjid();
                AsStageId = supervisorProjectForms.getSpfStaid();
                AsMilePostId = supervisorProjectForms.getSpfMilid();
                AsPkgId = supervisorProjectForms.getPcId();
                AsParentId = supervisorProjectForms.getFileParentId();
                AsLinkId = supervisorProjectForms.getSpfId();
                AsWjNum = supervisorProjectForms.getWjNum();
                fileInd = supervisorProjectForms.getFileInd();
                fbcode=supervisorProjectForms.getFbCode();
                AbSaveFlag = true;
                AbLcStatusFlag = true;
                break;
            case FL_FILES:
                AsSavePath = fileEnum.getFilePath();
                break;
            case FL_EVAL:
                AsFileType = "112";
                AsLinkId = request.getParameter("speid");
                String bfcid = request.getParameter("bfcid");
                AsPrjId = request.getParameter("spid");
                SupervisorProject supervisorProject = supervisorProjectService.selectByPrimaryKey(AsPrjId);
                String AsProjectName = supervisorProject.getProjectName();
                //查询该项目评价编号:
                SupervisorProjectEvaluation selectEvaluation = new SupervisorProjectEvaluation();
                selectEvaluation.setSpId(AsPrjId);
                int i = supervisorProjectEvaluationService.selectCount(selectEvaluation) +1;
                String s = StringUtil.autoGenericCode(i + "", 3);
                AsSavePath = FileUtils.getSaveFullFileName(3, bfcid, AsProjectName, AsFileType, "", ".doc", s);
                AbSaveFlag = true;
                break;
            case FL_SEAL:
                AsFileId = fileEnum.getFileId();
                AsSavePath = fileEnum.getFilePath();
                AbSealFlag = true;
                break;
            default:
                AsSavePath = fileEnum.getFilePath();
        }
        FileSaver fs = new FileSaver(request, response);
        fs.saveToFile(AsSavePath);
        fs.close();
        if (AbSaveFlag) {
            // 插入
            saveFile(AsSavePath, AsFileType, AsPrjId, AsStageId, AsMilePostId, AsPkgId, AsParentId, AsLinkId,fileInd);
            if (AbLcStatusFlag) {
                //修改流程阶段状态
                if (StringUtil.isNotBlank(AsWjNum) && AsWjNum != null) {
                    if("045".equals(AsFileType) || "039".equals(AsFileType)   ||   "042".equals(AsFileType)    ){
                        /*到货验收-------到货验收报告  材料进场  序列号验证记录  */
                        updateLcStatusDh(AsPrjId,AsStageId, AsMilePostId, AsWjNum,fbcode);
                    }else{
                        updateLcStatus(AsStageId, AsMilePostId, AsWjNum);
                    }

                }
            }
        }else{
            // 修改文件
            if(StringUtil.isNotBlank(fileId)){
                SupervisorFile supervisorFile = supervisorFileService.selectByPrimaryKey(fileId);
                supervisorFileService.parseFileToText(supervisorFile);
            }
        }
    }

    /**
     * 插入文档表
     *
     * @param pFilePath
     * @param pFileType
     * @param pPrjId
     * @param pStageId
     * @param pMilePostId
     * @param pPkgId
     * @param pParentId
     * @param pLinkId
     * @throws Exception
     */
    public void saveFile(String pFilePath, String pFileType, String pPrjId, String pStageId, String pMilePostId, String pPkgId, String pParentId, String pLinkId,Integer fileInd) throws Exception {
        SupervisorFile countFile = new SupervisorFile();
        countFile.setProjectId(pPrjId);
        countFile.setUrl(pFilePath);
        int countfile = supervisorFileService.selectCount(countFile);
        if (countfile == 0) {
            SupervisorFile AoFile = new SupervisorFile();
            //带.的后缀名
            String AsSuffix = FilePathUtil.getFileSufiix(pFilePath);
            //获取文件名称
            String AsFileName = FilePathUtil.getFileName(pFilePath);
            // 文件名称
            AoFile.setFileName(AsFileName);
            // 文件后缀
            AoFile.setFileType(AsSuffix);
            // 文件类型
            AoFile.setType(pFileType);
            // url
            AoFile.setUrl(pFilePath);
            //項目id
            AoFile.setProjectId(pPrjId);
            //阶段id
            AoFile.setStageId(pStageId);
            //里程id
            AoFile.setSpmId(pMilePostId);
            //分包id
            AoFile.setPcId(pPkgId);
            //父级id
            AoFile.setParentId(pParentId);
            // form 表Id
            AoFile.setLinkId(pLinkId);
            if(fileInd != null){
                AoFile.setInd(fileInd);
            }
            if (!"112".equals(pFileType)) {
                projectBigEventService.saveProejctBigEvent(pPrjId, pMilePostId, pStageId);
            }
            supervisorFileService.insertSelective(AoFile);
        }
        //材料设备进场检验报告
        if (pFileType.equals("039") && countfile == 0) {
            //获取材料设备进场检验报告插入数据
            List<List<String>> AlistTableData = WordUtil.getWordTableData(pFilePath, 1, 6);
            //获取合同比对报告文件地址
            SupervisorFile supervisorFile = new SupervisorFile();
            supervisorFile.setProjectId(pPrjId);
            supervisorFile.setPcId(pPkgId);
            supervisorFile.setType("044");
            int AiCnt = supervisorFileService.selectCount(supervisorFile);
            if (AiCnt == 1) {
                supervisorFile = supervisorFileService.selectOne(supervisorFile);
                String AsSaveContactPath = supervisorFile.getUrl();
                WordUtil.compareContract(AsSaveContactPath, AlistTableData);
            } else if (AiCnt == 0) {
                throw new Exception("非常抱歉，项目ID:" + pPrjId + "的项目未发现合同比对报告，无法进行合同比对。");
            } else if (AiCnt > 1) {
                throw new Exception("非常抱歉，项目ID:" + pPrjId + "的项目发现多个合同比对报告，仅支持一个合同进行比对，请删除对于的合同对比报告。");
            }
        }
        //  20220627  增加第一次上传文件的时间  和 更新最后一次上传时间
        SupervisorProject  project=supervisorProjectService.selectByPrimaryKey(pPrjId);
        if(StringUtils.isBlank(project.getUploadBeginTime())){
            project.setUploadBeginTime(com.qili.util.DateUtil.getCurrentDateString());
        }
        project.setUploadLastTime(com.qili.util.DateUtil.getCurrentDateString());
        supervisorProjectService.updateByPrimaryKey(project);
    }

    /**
     * @param AsStageId
     * @param AsMilePostId
     * @Author:zhaoyongke
     * @Description: 修改里程 阶段状态
     * @Date:21:24 2020/12/17
     */
    public void updateLcStatus(String AsStageId, String AsMilePostId, String fs_status) {
        SupervisorProjectMilepost supervisorProjectMilepost = supervisorProjectMilepostService.selectByPrimaryKey(AsMilePostId);
        String finishStatuslc = supervisorProjectMilepost.getFinishStatus();//
        String stepNum = supervisorProjectMilepost.getStepNum();
        String[] ayStatus = stepNum.split(",");
        String asPostStartIdx = fs_status.substring(0, 1);// 例如  10  20  截取  为  1 , 2
        String strsatus = ayStatus[Integer.valueOf(asPostStartIdx) - 1];
        // 该里程的状态为 进行中  或未开始 或 本文件类型为未开始的状态
        String fs= strsatus.substring(1, 2);
        if (fs.equals("0") && ("0".equals(finishStatuslc) || "1".equals(finishStatuslc)|| "3".equals(finishStatuslc))) {// 判断当前文件类型的状态
            ayStatus[Integer.valueOf(asPostStartIdx) - 1] = fs_status;// 更新文件类型状态
            String str = Arrays.toString(ayStatus).replace("[", "").replace("]", "").replace(" ", "");
            supervisorProjectMilepost.setStepNum(str);
        }

        if ("0".equals(finishStatuslc)) {
            supervisorProjectMilepost.setFinishStatus("1");//进行中
        }
        /*更新里程状态*/
        supervisorProjectMilepostService.updateByPrimaryKey(supervisorProjectMilepost);
        /*处理阶段状态*/
        SupervisorProjectStage stage = supervisorProjectStageService.selectByPrimaryKey(AsStageId);
        String finishStatusjd = stage.getFinishStatus();//
        if ("0".equals(finishStatusjd)) {
            stage.setFinishStatus("1");//进行中
            supervisorProjectStageService.updateByPrimaryKey(stage);
        }

    }

    /**
    * @Author:zhaoyongke
    * @Description:到货验收状态处理
    * @param AsStageId
    * @param AsMilePostId
    * @param fs_status
    * @Date:9:46 2021/2/6
    */
    public void updateLcStatusDh(String projectId,String AsStageId, String AsMilePostId, String fs_status,String  fbcode) {
        // 查询分包
        ProjectContract contract = new ProjectContract();
        contract.setCode(fbcode);
        contract.setProjectId(projectId);
        List<ProjectContract>  listcon = projectContractService.select(contract);
        if(listcon.size()>0){
            contract=listcon.get(0);
            // 查询分包表
            String stepNum = contract.getStepNum();
            // 数据库取出的完成状态
            String finishstatus = contract.getFinishStatus();
            String[] ayStatus = stepNum.split(",");
            String asPostStartIdx = fs_status.substring(0, 1);// 例如  10  20  截取  为  1 , 2
            String strsatus = ayStatus[Integer.valueOf(asPostStartIdx) - 1];
            // 该里程的状态为 进行中  或未开始 或 本文件类型为未开始的状态
            if (strsatus.substring(1, 2).equals("0") && ("0".equals(finishstatus) || "1".equals(finishstatus))) {// 判断当前文件类型的状态
                ayStatus[Integer.valueOf(asPostStartIdx) - 1] = fs_status;// 更新文件类型状态
                String str = Arrays.toString(ayStatus).replace("[", "").replace("]", "").replace(" ", "");
                contract.setStepNum(str);
            }
            if("0".equals(finishstatus)){
                contract.setFinishStatus("1");
                //进行中
            }
            /*更新分包*/
            projectContractService.updateByPrimaryKey(contract);
            /*更新里程状态*/
            SupervisorProjectMilepost supervisorProjectMilepost = supervisorProjectMilepostService.selectByPrimaryKey(AsMilePostId);
            if ("0".equals(supervisorProjectMilepost.getFinishStatus())) {
                supervisorProjectMilepost.setFinishStatus("1");//进行中
            }
            supervisorProjectMilepostService.updateByPrimaryKey(supervisorProjectMilepost);
            /*处理阶段状态*/
            SupervisorProjectStage stage = supervisorProjectStageService.selectByPrimaryKey(AsStageId);
            String finishStatusjd = stage.getFinishStatus();//
            if ("0".equals(finishStatusjd)) {
                stage.setFinishStatus("1");//进行中
                supervisorProjectStageService.updateByPrimaryKey(stage);
            }

        }


    }


    /**
     * @param doc
     * @param t
     * @Author:Zhangshuo
     * @Description:设置Region
     * @Date:14:12 2020/11/16
     */
    public <T> void loadRegion(WordDocument doc, T t, List<SupervisorProjectFormsData> formTabledata) {
        // 设置form 数据
        loadFromData(doc, t);
        // 设置table 数据
        loadTableData(doc, formTabledata);
    }

    /**
     * @param doc
     * @param evaluation
     * @param scoreList
     * @Description:设置Region
     */
    public void loadRegion(WordDocument doc, SupervisorProjectEvaluation evaluation, List<SupervisorProjectEvaluationScore> scoreList) {
        // 设置form 数据
        loadFromData(doc, evaluation);
        // 设置table 数据
        initTable(doc, scoreList);
    }

    /**
     * @param doc
     * @param t
     * @Author:zhaoyongke
     * @Description: 设置form 数据
     * @Date:13:02 2020/12/6
     */
    public <T> void loadFromData(WordDocument doc, T t) {
        //获取所有属性
        List<Field> properties = ClassUtils.getBookmarkFields(t.getClass(), true);
        for (int i = 0, len = properties.size(); i < len; i++) {
            Field AfdTmp = properties.get(i);
            Bookmark bk = AfdTmp.getAnnotation(Bookmark.class);
            String mark = bk.mark();
            DataRegion AdrItem = doc.openDataRegion(mark);
            String AsFieldValue = null;
            try {
                AsFieldValue = (String) AfdTmp.get(t);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            if (!isNull(AdrItem) && !isNull(AsFieldValue)) {
                AdrItem.setValue(AsFieldValue);
            }
        }
    }

    /**
     * @param doc
     * @param formTabledata
     * @Author:zhaoyongke
     * @Description: 设置table 数据
     * @Date:13:03 2020/12/6
     */
    public void loadTableData(WordDocument doc, List<SupervisorProjectFormsData> formTabledata) {
        if (formTabledata.size() > 0) {
            //获取各个表的分类数据
            Map<Integer, List<SupervisorProjectFormsData>> AmpTables = new HashMap<Integer, List<SupervisorProjectFormsData>>();
            for (SupervisorProjectFormsData table : formTabledata) {
                int AsTabelIndex = table.getTableIndex();
                if (AmpTables.containsKey(AsTabelIndex)) {
                    List<SupervisorProjectFormsData> AlstTmp = AmpTables.get(AsTabelIndex);
                    AlstTmp.add(table);
                } else {
                    List<SupervisorProjectFormsData> AlstTmp = new ArrayList<>();
                    AlstTmp.add(table);
                    AmpTables.put(AsTabelIndex, AlstTmp);
                }
            }
            //遍历每个表的数据
            for (Map.Entry<Integer, List<SupervisorProjectFormsData>> entry : AmpTables.entrySet()) {
                Integer AiIdx = entry.getKey();
                List<SupervisorProjectFormsData> AlistTable = entry.getValue();
                initTable(doc, AiIdx, AlistTable);
            }
        }
    }


    /**
     * @param doc
     * @param piIdx
     * @param plistTable
     * @Author:zhaoyongke
     * @Description:
     * @Date:18:00 2020/12/6
     */
    public void initTable(WordDocument doc, Integer piIdx, List<SupervisorProjectFormsData> plistTable) {
        String AsTabBookMarke = "PO_T" + piIdx;
        DataRegion dataRegion = doc.openDataRegion(AsTabBookMarke);
        Table table = dataRegion.openTable(1); //index代表当前书签中table位置的索引，从1开始
        Integer AiRowsCnt = plistTable.size();
        OrderByData1(plistTable);
        for (int i = 0; i < AiRowsCnt; i++) {
            SupervisorProjectFormsData AoTmp = plistTable.get(i);
            JSONObject AjsRowData = (JSONObject) JSONObject.toJSON(AoTmp);
            Integer AiColCnt = AoTmp.getTableCos();
            Integer AiRowIdx = AoTmp.getTableRow();
            //在第2行的最后一个单元格下插入新行
            table.insertRowAfter(table.openCellRC(AiRowIdx - 1 + i, AiColCnt));
            for (int j = 1; j <= AiColCnt; j++) {
                Object AobjTmp = AjsRowData.get("data" + j);
                if (!isNull(AobjTmp)) {
                    String AsValue = AjsRowData.get("data" + j).toString();
                    table.openCellRC(AiRowIdx + i, j).setValue(AsValue);
                }
            }
        }
    }

    /**
     * @param plistTable
     * @Description:
     * @Author:Zhangshuo
     * @Date:19:36 2020-12-18
     */
    private void OrderByData1(List<SupervisorProjectFormsData> plistTable) {
        Collections.sort(plistTable, new Comparator<SupervisorProjectFormsData>() {
            @Override
            public int compare(SupervisorProjectFormsData u1, SupervisorProjectFormsData u2) {
                try {
                    if (isInt(u1.getData1()) && isInt(u2.getData1())) {
                        int diff = Integer.valueOf(u1.getData1()) - Integer.valueOf(u2.getData1());
                        if (diff > 0) {
                            return 1;
                        } else if (diff < 0) {
                            return -1;
                        }
                    }
                    return 0; //相等为0
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                    return 0;
                }
            }
        });
    }

    /**
     * @param str
     * @Author:zhaoyongke
     * @Description:
     * @Date:16:55 2021/1/19
     */
    private static boolean isInt(String str) {
        try {
            Integer.valueOf(str);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * @param doc
     * @param plistTable
     * @Author:zhaoyongke
     * @Description:
     * @Date:18:00 2020/12/6
     */
    public void initTable(WordDocument doc, List<SupervisorProjectEvaluationScore> plistTable) {
        DataRegion dataRegion = doc.openDataRegion("PO_table");
        Table table = dataRegion.openTable(1); //index代表当前书签中table位置的索引，从1开始
        Integer AiRowsCnt = plistTable.size();

        for (int i = 0; i < AiRowsCnt; i++) {
            SupervisorProjectEvaluationScore score = plistTable.get(i);
            Integer AiColCnt = 6;
            Integer AiRowIdx = 3;
            //在第2行的最后一个单元格下插入新行
            BaseDict select = new BaseDict();
            select.setBadtCode(score.getBdBadtCode());
            BaseDict baseDict = baseDictService.selectOne(select);
            table.insertRowAfter(table.openCellRC(AiRowIdx - 1 + i, AiColCnt));
            setTableData(AiRowIdx, table, i, score, baseDict.getBadtName());
        }
    }

    /**
     * 设置表格内容
     *
     * @param table
     * @param i
     * @param score
     */
    public void setTableData(Integer aiRowIdx, Table table, int i, SupervisorProjectEvaluationScore score, String rowTitle) {
        table.openCellRC(aiRowIdx + i, 1).setValue(rowTitle);
        if (StringUtils.isBlank(score.getSpesScore())) {
            score.setSpesScore("0");
        }
        BigDecimal spesScore = new BigDecimal(score.getSpesScore());
        if (!isNull(spesScore)) {
            int j = 5;
            if (spesScore.compareTo(new BigDecimal("90")) != -1) {
                j = 2;
            } else if ((spesScore.compareTo(new BigDecimal("90")) == -1) && (spesScore.compareTo(new BigDecimal("80")) != -1)) {
                j = 3;
            } else if ((spesScore.compareTo(new BigDecimal("80")) == -1) && (spesScore.compareTo(new BigDecimal("60")) != -1)) {
                j = 4;
            }
            table.openCellRC(aiRowIdx + i, j).setValue(spesScore.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
            if (StringUtils.isNotBlank(score.getRemark())) {
                table.openCellRC(aiRowIdx + i, 6).setValue(score.getRemark());
            }
        }
    }

    /**
     * @param request
     * @Description:
     * @Author:Zhangshuo
     * @Date:19:27 2020-12-15
     */
    @RequestMapping("/test1")
    public String test1(HttpServletRequest request) {
        FileMakerCtrl fmCtrl = new FileMakerCtrl(request);
        fmCtrl.setServerPage(request.getContextPath() + "/poserver.zz");
        String id = request.getParameter("id");

        if (id != null && id.length() > 0) {
            WordDocument doc = new WordDocument();
            //禁用右击事件
            doc.setDisableWindowRightClick(true);
            //给数据区域赋值，即把数据填充到模板中相应的位置
            doc.openDataRegion("PO_company").setValue("北京卓正志远软件有限公司  " + id);
            fmCtrl.setSaveFilePage("/sys/office/test2?id=" + id);
            fmCtrl.setWriter(doc);
            fmCtrl.setJsFunction_OnProgressComplete("OnProgressComplete()");
            fmCtrl.setFileTitle("newfilename.doc");
            fmCtrl.fillDocument("d:\\doc\\template.doc", DocumentOpenType.Word);
            fmCtrl.setTagId("FileMakerCtrl1");
            request.setAttribute("pageoffice", fmCtrl.getHtmlCode("FileMakerCtrl1"));
        }
        return "office/save";
    }

    @RequestMapping("/test2")
    public void test2(HttpServletRequest request, HttpServletResponse response) {
        FileSaver fs = new FileSaver(request, response);
        String id = request.getParameter("id");
        String err = "";
        if (id != null && id.length() > 0) {
            fs.saveToFile("d:\\doc\\template1.doc");
        } else {
            err = "<script>alert('未获得文件名称');</script>";
        }
        fs.close();
    }

}
